package com.avocado.base.repository;

import java.util.List;

import org.springframework.data.jpa.repository.Query;


import com.avocado.persistence.repository.BaseRepository;
import com.avocado.base.entity.Resources;
import com.avocado.base.enums.ResourcesType;
import org.springframework.data.repository.query.Param;


public interface ResourcesRepository extends BaseRepository<Resources, Long> {
	
	/**
	 * 按资源代码称统计
	 * @param code
	 * @return
	 */
	@Query("select count(1) from Resources where code=:code")
	Long getCountByCode(@Param("code")String code);
	
	/**
	 * 排除传入ID，按资源代码称统计
	 * @param code
	 * @param excludeId
	 * @return
	 */
	@Query("select count(1) from Resources where code=:code and id!=:excludeId")
	Long getCountByCodeAndExcludeId(@Param("code")String code,@Param("excludeId")Long excludeId);
	
	/**
	 * 查找所有
	 */
	@Query("from Resources t order by t.sortOrder")
	List<Resources> findAll();
	
	/**
	 * 按父ID查找所有
	 * @param parentId
	 * @return
	 */
	@Query("from Resources t  where t.parentId=:parentId  order by t.sortOrder")
	List<Resources> findAllByParentId(@Param("parentId")Long parentId);
	
	/**
	 * 按父ID统计
	 * @param parentId
	 * @return
	 */
	@Query("select count(1) from Resources where parentId=:parentId")
	Long getCountByParentId(@Param("parentId")Long parentId);
	
	/**
	 * 按资源类型查找所有资源
	 * @param resourcesType
	 * @return
	 */
	@Query("from Resources t  where t.type=:resourcesType  order by t.sortOrder")
	List<Resources> findAll(@Param("resourcesType")ResourcesType resourcesType);
	
	/**
	 * 按资源类型查找与传入角色关联的所有资源
	 * @param resourcesType
	 * @param roleId
	 * @return
	 */
	@Query("from Resources t where t.type=:resourcesType and t.id in (select resources.id from ResourcesRole where role.id=:roleId) order by t.sortOrder")
	List<Resources> findAll(@Param("resourcesType")ResourcesType resourcesType,@Param("roleId")Long roleId);
	
	/**
	 * 按资源类型查找与传入角色关联的所有资源
	 * @param resourcesType
	 * @param roleIdList
	 * @return
	 */
	@Query("from Resources t where t.type=:resourcesType and t.id in(select rr.id.resourcesId from ResourcesRole rr where rr.id.roleId in (:roleIdList)) order by t.sortOrder")
	List<Resources> findAll(@Param("resourcesType")ResourcesType resourcesType,@Param("roleIdList")List<Long> roleIdList);
	
	
	/**
	 * 按资源类型查找与传入用户关联的所有资源
	 * @param resourcesType
	 * @param userName
	 * @return
	 */
	@Query("from Resources t where t.type=:resourcesType and t.id in(select rr.id.resourcesId from ResourcesRole rr where rr.id.roleId in (select ur.id.roleId from UserRole ur where ur.user.name=:userName)) order by t.sortOrder")
	List<Resources> findAll(@Param("resourcesType")ResourcesType resourcesType,@Param("userName")String userName);
	
	
	@Query("from Resources t where t.id in(select rr.id.resourcesId from ResourcesRole rr where rr.id.roleId in (select ur.id.roleId from UserRole ur where ur.user.name=:userName)) order by t.sortOrder")
	List<Resources> findAll(@Param("userName")String userName);
	

}
